/*\
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
*/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
      struct ListNode *p = l1; //Á´±í1 
    struct ListNode *q = l2; //Á´±í2 
    int temp = 0; //ÓÃÓÚÅÐ¶ÏÊÇ·ñ½øÎ»µÄÊý
    struct ListNode *head = NULL;
    struct ListNode *last = NULL;
    while( p != NULL || q != NULL)
    {
        if (p != NULL && q != NULL)  //Á½¸öÁ´±í¶¼²»Îª¿ÕµÄÊ±ºò£¬ 
        {
            temp +=  p -> val + q -> val;
             p = p -> next;
       	q = q -> next;
            printf("1ok\n");

        } else if (p == NULL && q != NULL) 
        {
            temp += q -> val;
            q = q -> next;
            printf("3ok\n");
        } else if ( p != NULL && q == NULL)
        {
        	printf("2ok\n");
            temp += p -> val;
            p = p -> next;
        }
        struct ListNode *data = (struct ListNode*) malloc(sizeof(struct ListNode));
        data -> val = temp % 10;
        data -> next = NULL;
        temp = temp / 10;
        if (head  == NULL)
        {
            head = data;
            last = data;
        } else 
        {
             last -> next = data; 
	last = data;   
        }           
    }

    if (temp != 0) 
    {
    	struct ListNode *data = (struct ListNode*) malloc(sizeof(struct ListNode));
        	data -> val = temp;
        	data -> next = NULL;
        	last -> next = data;
    }
    return head;
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
typedef struct ListNode* ListPointer;
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int carry=0,buffer;
    ListPointer head,temp,last;
    head=(struct ListNode*)malloc(sizeof(struct ListNode));
    head->val=0;
    head->next=NULL;
    last=head;
    while(l1!=NULL || l2!=NULL || carry){
        temp=(struct ListNode*)malloc(sizeof(struct ListNode));
        temp->next=NULL;
        buffer=carry;
        if(l1!=NULL) buffer += l1->val;
        if(l2!=NULL) buffer += l2->val;
        temp->val=buffer%10;
        carry=(int)buffer/10;
        last->next=temp;
        if(l1!=NULL) l1=l1->next;
        if(l2!=NULL) l2=l2->next;
        last=temp;
    }
    return head->next;
}
